package com.hong.utils.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: Administrator
 * @Date: 2018/7/22 23:02
 * @Description:
 */
public class SemaphoreExample1 {
    public static void main(String[] args) {
        final  SemapphoreLock lock = new SemapphoreLock();

        for (int i =0;i<2;i++){
            new Thread(){
                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName()+"is running");
                        lock.lock();
                        System.out.println(Thread.currentThread().getName()+" get the #SemaphoreLock");
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }

                    System.out.println(Thread.currentThread().getName()+" release #SemaphoreLock");
                }
            }.start();
        }
    }

    static class SemapphoreLock{
        private final  Semaphore semaphore = new Semaphore(1);

        public void lock() throws InterruptedException {
            semaphore.acquire();
        }

        public void unlock(){
            semaphore.release();
        }
    }

    private synchronized static void  m(){
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
